package com.chenyuxin.ilp.exception;



import com.chenyuxin.ilp.model.enums.exception.ExceptionEnums;
import com.chenyuxin.ilp.model.pojo.Result;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpStatus;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.multipart.MaxUploadSizeExceededException;

@RestControllerAdvice
@Slf4j
public class GlobalExceptionHandler {

    @ExceptionHandler(Exception.class)
    @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
    public Result exception(Exception exception){
        log.error(exception.toString());
        exception.printStackTrace();
        return Result.fail(ExceptionEnums.SYSTEM_ERROR);
    }
    @ExceptionHandler(BaseException.class)
    public Result exception(BaseException exception){
        log.error(exception.toString());
        exception.printStackTrace();
        return Result.fail(exception.getCode(),exception.getMessage());
    }
    @ExceptionHandler(MethodArgumentNotValidException.class)
    @ResponseStatus(HttpStatus.OK)
    public Result handleMethodArgumentNotValidException(MethodArgumentNotValidException ex) {
        BindingResult bindingResult = ex.getBindingResult();
        FieldError fieldError = bindingResult.getFieldError();
        String defaultMessage = fieldError.getDefaultMessage();
        // 根据需要构建你的响应对象
        log.error(fieldError.toString());
        return Result.fail(40300,defaultMessage);
    }
    @ExceptionHandler(MaxUploadSizeExceededException.class)
    public Result exception(MaxUploadSizeExceededException exception){
        return Result.fail(ExceptionEnums.UPLOAD_FILE_BIG);
    }

}
